package com.cqhz.quwan.ui.activity

import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlertDialog
import android.content.DialogInterface
import android.content.Intent
import android.os.Handler
import android.os.Message
import android.support.v7.widget.LinearLayoutManager
import android.text.Editable
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import com.blankj.utilcode.util.KeyboardUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.cqhz.quwan.APP
import com.cqhz.quwan.ActivityInject
import com.cqhz.quwan.R
import com.cqhz.quwan.common.KeyContract
import com.cqhz.quwan.model.*
import com.cqhz.quwan.mvp.BasketballSelectedContract
import com.cqhz.quwan.mvp.BasketballSelectedPresenter
import com.cqhz.quwan.mvp.mine.AlipayContract
import com.cqhz.quwan.mvp.mine.AlipayPresenter
import com.cqhz.quwan.ui.base.AbsActivity
import com.cqhz.quwan.ui.login.LoginActivity
import com.cqhz.quwan.ui.widget.LoadMoreDoneView
import com.cqhz.quwan.util.*
import kotlinx.android.synthetic.main.activity_bonus_optimization_basketball.*
import me.militch.quickcore.core.HasDaggerInject
import java.math.BigDecimal
import javax.inject.Inject

/**
 * 奖金优化-篮球
 * Created by Guojing on 2018/12/24.
 */
class BonusOptimizationBasketballActivity : AbsActivity(), AlipayContract.View, BasketballSelectedContract.View, HasDaggerInject<ActivityInject>, PayEventSubscribe {

    @Inject
    lateinit var alipayPresenter: AlipayPresenter
    @Inject
    lateinit var basketballSelectedPresenter: BasketballSelectedPresenter
    private var loginBean: LoginBean? = null
    private var mPagePosition: Int = 0
    private var mSelectList = ArrayList<BallMatchBean>()
    private lateinit var mBonusOptimizationList: ArrayList<BallSelectedBean>
    private lateinit var mBonusOptimizationListAdapter: BaseQuickAdapter<*, *>

    // 投注需要上传的参数
    private var playType: Int = 0
    private var betTimes: Int = 1// 投注倍数
    private var minAmount: Int = 0// 投注趣豆额
    private var payAmount: Int = 0// 投注趣豆额
    private var betNums: Int = 0//
    private var betBunch: String = ""
    private var isBonusOptimize: String = "1"
    private var bonusOptimizeType: String = "0"

    private val mHandler: Handler = @SuppressLint("HandlerLeak")
    object : Handler() {
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            when (msg?.what) {
                MSG_UPDATE_UI -> {
                    mBonusOptimizationListAdapter.notifyDataSetChanged()
                    onDataChanged()
                }
                MSG_UPDATE_AMOUNT -> {
                    et_pay_amount.setText(payAmount.toString())
                }
            }
        }
    }

    companion object {
        const val MSG_UPDATE_UI = 0x10001
        const val MSG_UPDATE_AMOUNT = 0x10002
    }

    override fun inject(t: ActivityInject?) {
        t?.inject(this)
    }

    override fun layout(): Int {
        return R.layout.activity_bonus_optimization_basketball
    }

    override fun initView() {
        alipayPresenter.attachView(this)
        basketballSelectedPresenter.attachView(this)
        if (APP.get()!!.loginInfo != null) {
            loginBean = APP.get()!!.loginInfo
        }

        initData()
        initAdapter()
        setOnClick()
    }

    private fun initData() {
        mBonusOptimizationList = ArrayList<BallSelectedBean>()
        playType = intent.getStringExtra(KeyContract.PlayType).toInt()
        payAmount = intent.getStringExtra(KeyContract.Money).toInt()
        betBunch = intent.getStringExtra(KeyContract.String)
        mSelectList.addAll(intent.getParcelableArrayListExtra(KeyContract.List))
        // 1：胜负；2：让分胜负；3：胜分差；4：大小分；5：混合过关；6：单关；
        tv_selected.text = mSelectList.size.toString() + "场，" + when (playType) {
            1 -> "胜负"
            2 -> "让分胜负"
            3 -> "胜分差"
            4 -> "大小分"
            5 -> "混合过关"
            6 -> "单关"
            else -> ""
        } + "，" + betBunch.replace("-", "串")

        val ballSelectedList = ArrayList<BallSelectedBean>()
        for (i in 0 until mSelectList.size) {
            if (mSelectList[i].selectedNumber > 0) {
                val odds = ArrayList<String>()
                val selectedItemList = ArrayList<BallSelectedItemBean>()
                for (j in 0 until mSelectList[i].selected!!.size) {
                    if (mSelectList[i].selected!![j] == true) {
                        odds.add(mSelectList[i].oddsMap!![j]!!)
                        selectedItemList.add(BallSelectedItemBean(mSelectList[i].week, mSelectList[i].matchField, mSelectList[i].hostTeam, mSelectList[i].guestTeam, j.getCheckBoxTextValueLabel(), mSelectList[i].oddsMap!![j]!!, j.toString(), mSelectList[i].code))
                    }
                }
                ballSelectedList.add(BallSelectedBean(false, selectedItemList.size.toString(), "", "", selectedItemList))
            }
        }
        val tempSelectedList = arrayOfNulls<Array<Any>>(ballSelectedList.size)
        for (i in 0 until ballSelectedList.size) {
            tempSelectedList[i] = ballSelectedList[i].selectedList.toTypedArray()
        }
        val betString = betBunch.replace(",", "")
        val betBunches = betString.split("-1".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() // 用,分割
        var bunchList = BasketBallBetUtils.getBetList(betBunches, tempSelectedList)

        for (i in 0 until bunchList.size) {
            val odds = ArrayList<String>()
            val selectedItemList = ArrayList<BallSelectedItemBean>()
            for (j in 0 until bunchList[i].size) {
                var item = bunchList[i][j] as BallSelectedItemBean
                odds.add(item.profitOdds)
                selectedItemList.add(item)
            }
            var singlePrize = 200.00
            var totalPrize = 200.00

            for (k in 0 until odds.size) {
                singlePrize *= odds[k].toDouble()
            }
            totalPrize = singlePrize * 1
            mBonusOptimizationList.add(BallSelectedBean(false, "1", singlePrize.toString().formatMoney(), totalPrize.toString().formatMoney(), selectedItemList))
        }

        minAmount = BigDecimal(mBonusOptimizationList.size).multiply(BigDecimal(200)).toInt()
        tv_min_amount.text = minAmount.toString().formatNoZero() + "趣豆"
    }

    private fun initAdapter() {
        // 当前页面列表的空布局
        var emptyView = LayoutInflater.from(this).inflate(R.layout.layout_none, rv_content.parent as? ViewGroup, false) as View
        var ivNone = emptyView.findViewById(R.id.iv_none) as ImageView
        ivNone.setImageResource(0)

        // 当前页面列表的数据和适配器
        mPagePosition = intent.getIntExtra(KeyContract.Position, 0)
        mBonusOptimizationListAdapter = CommonAdapterHelper.getBonusOptimizationListAdapter(this, mBonusOptimizationList, true)
        mBonusOptimizationListAdapter.emptyView = emptyView
        mBonusOptimizationListAdapter.setLoadMoreView(LoadMoreDoneView())

        // 当前页面列表适配器的事件
        rv_content.layoutManager = LinearLayoutManager(this)
        rv_content.isNestedScrollingEnabled = false// 让NestedScrollView滑动顺滑
        rv_content.adapter = mBonusOptimizationListAdapter
        mBonusOptimizationListAdapter.setOnItemChildClickListener { _, view, position ->
            val item = mBonusOptimizationList[position]
            when (view.id) {
                R.id.action_minus -> {
                    var betNum = Integer.valueOf(item.betNum)
                    if (betNum > 1) {
                        betNum -= 1
                        payAmount -= 200
                        item.betNum = betNum.toString()

                        var totalPrize = BigDecimal(item.singlePrize).multiply(BigDecimal(betNum)).toDouble()
                        item.totalPrize = totalPrize.toString().formatMoney()
                    }
                    radioGroup.clearCheck()
                    isBonusOptimize = "1"
                    mHandler.sendEmptyMessage(MSG_UPDATE_UI)
                    mHandler.sendEmptyMessage(MSG_UPDATE_AMOUNT)
                }
                R.id.action_add -> {
                    var betNum = Integer.valueOf(item.betNum) + 1
                    payAmount += 200
                    item.betNum = betNum.toString()

                    var totalPrize = BigDecimal(item.singlePrize).multiply(BigDecimal(betNum)).toDouble()
                    item.totalPrize = totalPrize.toString().formatMoney()
                    radioGroup.clearCheck()
                    isBonusOptimize = "1"
                    mHandler.sendEmptyMessage(MSG_UPDATE_UI)
                    mHandler.sendEmptyMessage(MSG_UPDATE_AMOUNT)
                }
                R.id.action_goto_expand, R.id.action_goto_expand2 -> {
                    item.isShowList = !item.isShowList
                    mBonusOptimizationListAdapter.notifyDataSetChanged()
                }
            }
        }

        bonusOptimizationAverage()
        mHandler.sendEmptyMessage(MSG_UPDATE_UI)
        mHandler.sendEmptyMessage(MSG_UPDATE_AMOUNT)
    }

    /**
     * 当选中状态改变时
     */
    private fun onDataChanged() {
        var minPrize = mBonusOptimizationList[0].totalPrize.toDouble()
        var maxPrize = 0.00
        for (i in 0 until mBonusOptimizationList.size) {
            if (minPrize > mBonusOptimizationList[i].totalPrize.toDouble()) {
                minPrize = mBonusOptimizationList[i].totalPrize.toDouble()
            }
            maxPrize = BigDecimal(maxPrize).add(BigDecimal(mBonusOptimizationList[i].totalPrize)).toDouble()
        }

        betNums = payAmount / 200

        tv_bet_times.text = "${betNums}注"
        tv_pay_amount.text = "${payAmount}趣豆"
        tv_total_prize.text = minPrize.toString().formatMoney() + "~" + maxPrize.toString().formatMoney()
    }

    /**
     * 设置点击事件
     */
    private fun setOnClick() {
        action_closed.setOnClickListener { finish() }
        action_show_dialog.setOnClickListener {
            createDialog(title = "奖金优化规则",
                    msg = "1、平均优化  使每个单注的奖金趋于一致\n2、博热优化  使概率最高的单注奖金最大化，其它单注的奖金保本\n3、博冷优化  使奖金最高的单注奖金最大化，其它单注的奖金保本",
                    pos = "我知道了",
                    ok = { _, _ -> },
                    no = { _, _ -> }).show()
        }

        radioGroup.setOnCheckedChangeListener { _, checkedId ->
            when (checkedId) {
                R.id.action_select_average -> {
                    bonusOptimizationAverage()
                }
                R.id.action_select_hot -> {
                    if (!BasketBallBetUtils.isSupportHotOrCold(mBonusOptimizationList, payAmount)) {
                        showToast("该玩法不支持博热优化")
                        action_select_hot.isChecked = false
                        action_select_cold.isChecked = false
                        return@setOnCheckedChangeListener
                    }
                    isBonusOptimize = "0"
                    bonusOptimizeType = "1"
                    initBonusOptimizationList()
                    BasketBallBetUtils.hotOrColdOptimize(mBonusOptimizationList, BigDecimal(payAmount), 1)
                }
                R.id.action_select_cold -> {
                    if (!BasketBallBetUtils.isSupportHotOrCold(mBonusOptimizationList, payAmount)) {
                        showToast("该玩法不支持博冷优化")
                        action_select_hot.isChecked = false
                        action_select_cold.isChecked = false
                        return@setOnCheckedChangeListener
                    }
                    isBonusOptimize = "0"
                    bonusOptimizeType = "2"
                    initBonusOptimizationList()
                    BasketBallBetUtils.hotOrColdOptimize(mBonusOptimizationList, BigDecimal(payAmount), 2)
                }
            }
            mHandler.sendEmptyMessage(MSG_UPDATE_UI)
        }
        action_minus.setOnClickListener {
            KeyboardUtils.hideSoftInput(this)
            if (payAmount > minAmount) {
                payAmount -= 200
            }
            radioGroup.clearCheck()
            isBonusOptimize = "1"
            et_pay_amount.setText("$payAmount")

            onDataChanged()
        }
        action_add.setOnClickListener {
            KeyboardUtils.hideSoftInput(this)
            payAmount += 200
            radioGroup.clearCheck()
            isBonusOptimize = "1"
            et_pay_amount.setText("$payAmount")

            onDataChanged()
        }
        action_goto_pay.setOnClickListener {
            commitOrder()
        }

        et_pay_amount.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                try {
                    var value = s?.toString()?.toInt() ?: 0
                    payAmount = s?.toString()?.toInt() ?: 0
                    if (value == 0) {
                        payAmount = minAmount
                        et_pay_amount.setText(payAmount.toString())
                    }
                } catch (e: NumberFormatException) {
                    payAmount = minAmount
                }

                onDataChanged()
            }

        })
        et_pay_amount.setOnEditorActionListener { view: View?, i: Int?, event: KeyEvent? ->
            when (i) {
                EditorInfo.IME_ACTION_DONE -> {
                    et_pay_amount.clearFocus()
                    KeyboardUtils.hideSoftInput(this)
                }
            }
            false
        }
    }

    /**
     * 平均优化
     */
    private fun bonusOptimizationAverage() {
        var betNum = payAmount / 200 - mBonusOptimizationList.size// 待分配的注数
        isBonusOptimize = "0"
        bonusOptimizeType = "0"
        initBonusOptimizationList()
        BasketBallBetUtils.prizeOptimize(mBonusOptimizationList, betNum)
    }

    /**
     * 初始化数据列表
     */
    private fun initBonusOptimizationList() {
        for (i in 0 until mBonusOptimizationList.size) {
            var item = mBonusOptimizationList[i]
            item.betNum = "1"
            item.totalPrize = item.singlePrize
        }
    }

    /**
     * 提交订单
     */
    private fun commitOrder() {

        when {
            payAmount == 0 -> {
                showToast("投注金额不能为空")
                return
            }
            loginBean == null -> {
                toIntent(LoginActivity::class.java)
                return
            }
        }

        val args = HashMap<String, String>()
        args["userId"] = loginBean!!.userId ?: ""
        args["lotteryId"] = "24"
        args["period"] = "24"
        args["buyWay"] = "0"
        args["payAmount"] = payAmount.toString()
        args["betNum"] = betNums.toString()
        args["betTimes"] = betTimes.toString()
        args["betBunch"] = betBunch

        val betOrders = ArrayList<BetOrder>()
        for (i in 0 until mSelectList.size) {
            if (mSelectList[i].selectedNumber > 0) {
                var redNum = ""
                for (j in 0 until mSelectList[i].selected!!.size) {
                    if (mSelectList[i].selected!![j] == true) {
                        redNum += if (redNum.isEmpty()) j.toString() else ",$j"
                    }
                }
                betOrders.add(BetOrder(mSelectList[i].code, redNum, playType))
            }
        }

        args["orderBetJson"] = betOrders.json()
        args["isBonusOptimize"] = isBonusOptimize
        args["bonusOptimizeType"] = bonusOptimizeType

        val orders = ArrayList<bonusOptimizeBetOrder>()
        for (i in 0 until mBonusOptimizationList.size) {
            val items = ArrayList<bonusOptimizeBetOrderItem>()
            for (j in 0 until mBonusOptimizationList[i].selectedList.size) {
                items.add(bonusOptimizeBetOrderItem(mBonusOptimizationList[i].selectedList[j].redNum, mBonusOptimizationList[i].selectedList[j].period))
            }
            orders.add(bonusOptimizeBetOrder(mBonusOptimizationList[i].betNum, items))
        }
        args["bonusOptimizeBetJson"] = orders.json()

        action_goto_pay.isEnabled = false
        basketballSelectedPresenter.postOrder(args)
    }

    override fun toPay(orderResp: OrderResp) {
        val intent = Intent(this, GoPaymentActivity::class.java)
        intent.putExtra(KeyContract.Amount, orderResp.payAmount?.toDouble())
        intent.putExtra(KeyContract.ActualAmount, orderResp.payAmount?.toDouble())
        intent.putExtra(KeyContract.LotteryName, when (mPagePosition) {
            0 -> "竞猜篮球-混合过关"
            1 -> "竞猜篮球-单关"
            2 -> "竞猜篮球-胜负"
            3 -> "竞猜篮球-让球胜负"
            4 -> "竞猜篮球-大小分"
            5 -> "竞猜篮球-胜分差"
            else -> "其他"
        })
        intent.putExtra(KeyContract.OrderId, orderResp.id)
        startActivity(intent)
        finishActivity()
    }

    override fun setCommitEnable() {
        action_goto_pay.isEnabled = true
    }

    /**
     *
     * 创建弹出框
     */
    private fun createDialog(title: String = "", msg: String = "", pos: String = "", neg: String = "", ok: (DialogInterface, Int) -> Unit, no: (DialogInterface, Int) -> Unit): AlertDialog {
        return AlertDialog.Builder(this)
                .setTitle(title).setMessage(msg)
                .setPositiveButton(pos, ok)
                .setNegativeButton(neg, no).create()
    }

    /**
     * 绑定支付宝
     */
    override fun bindAlipay() {
        createDialog(title = "温馨提示",
                msg = "为了账户安全，请绑定支付宝",
                pos = "确认", neg = "取消",
                ok = { _, _ -> alipayPresenter.auth4alipay() },
                no = { _, _ -> }).show()
    }

    private fun finishActivity() {
        setResult(Activity.RESULT_OK, Intent())
        finish()
    }

    override fun doPayFinish() {
        finishActivity()
    }

    override fun alipayAuthCallBack(authData: AlipayAuthData) {
        basketballSelectedPresenter.bindAlipay(APP.get()!!.loginInfo!!.userId!!, authData)
    }

    override fun onResume() {
        super.onResume()
        if (APP.get()!!.loginInfo != null) {
            loginBean = APP.get()!!.loginInfo
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        alipayPresenter.detachView()
        basketballSelectedPresenter.detachView()
        PayEventObserver.unregister(this)
    }
}
